<?php
namespace Model\Saver;

use Doctrine\DBAL\Connection;
use Model\Entity\Message;

/**
 * Description of DoctrineDbalSaver
 *
 * @author pahhan
 */
class DoctrineDbalSaver extends AbstractSaver
{
    /**
     *
     * @var \Doctrine\DBAL\Connection
     */
    private $conn;

    function __construct(Connection $conn)
    {
        $this->conn = $conn;
    }

    protected function saveOne(Message $message)
    {
        $c = $this->conn
                ->executeQuery('SELECT id FROM message WHERE url_id = ? AND external_id = ?',
                        array($message->getUrlId(), $message->getExternalId())
                )
                ->rowCount();

        if( $c ) {
            throw new MessageSavedException(sprintf('Message with url_id = %d and external_id = %s already saved', $message->getUrlId(), $message->getExternalId()));
        }

        $this->conn->insert('message', $this->getInsertArary($message));
    }

    private function getInsertArary(Message $message)
    {
        $out = array(
            'url_id' => $message->getUrlId(),
            'external_id' => $message->getExternalId(),
            'site_id' => $message->getSiteId(),
            'title' => $message->getTitle(),
            'content' => $message->getContent(),
            'tags' => $message->getTags(),
        );

        if( $message->getPublishedAt() ) {
            $out['published_at'] = $message->getPublishedAt()->format('Y-m-d H:i:s');
        }

        if( $message->getUpdatedAt() ) {
            $out['updated_at'] = $message->getUpdatedAt()->format('Y-m-d H:i:s');
        }

        return $out;
    }
}

